package com.tedu.webDemo.controller;

import java.util.ArrayList;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CartController {
	//把商品放到session中
	@RequestMapping("/add")
	//localhost:1313/add?name=mate10
	public String add(String name,HttpSession session) {
		//从session中取商品
		ArrayList<String> cartList=
				(ArrayList<String>) 
				session.getAttribute("cartList");
		//第一次执行add(),cartList=null
		if (cartList==null) {
			cartList=new ArrayList<String>();
			//把集合保存到session中
			session.setAttribute("cartList", cartList);
		}
		//把商品放到集合中
		cartList.add(name);
		return "添加商品到session中";
	}
	//从session中取出商品
	@RequestMapping("/list")
	public String list(
			HttpServletRequest request,
			HttpSession session) {
		String string="";
		//获取cooke用request
		Cookie[] cookies=request.getCookies();
		if (cookies!=null) {
			for (Cookie cookie:cookies) {
				String name=cookie.getName();
				String value=cookie.getValue();
				string=string+name+":"+value+"<br>";
			}
		}
		
		
		//从session中找到集合
		ArrayList<String> cartList=
				(ArrayList<String>) 
				session.getAttribute("cartList");
		//用户可能没有添加商品
		if (cartList !=null) {
			//从集合中取出商品
			for(String  name:cartList) {
				string=string+name+"<br>";
			}
		}
		return string;
		
	}

}







